$.jgrid.defaults.responsive = true;
$.jgrid.defaults.styleUI = 'Bootstrap';

var suminfo;//按物料查看一共有多少条,分页时要用
var allResponse;//按物料查后台获取数据,放到这个变量上

$(document).ready(function () {
    var requestId = $('#requestId').val();
    var colModel = [{
        label: '物料代码',
        name: 'materialNo',
        index: 'MATERIAL_NO',
        width: 80,
    },
        {
            label: '物料名称',
            name: 'materialName',
            index: 'MATERIAL_NAME',
            width: 80,
        },
        {
            label: '型规',
            name: 'character',
            index: 'CHARACTER',
            width: 80
        },
        {
            label: '数量',
            name: 'requestAmount',
            index: 'REQUEST_AMOUNT',
            width: 80
        },
        {
            label: '单位',
            name: 'unit',
            index: 'UNIT',
            width: 80
        },
        {
            label: '起拍价',
            name: 'startPrice',
            index: 'START_PRICE',
            width: 80
        },
        {
            label: '当前最低价',
            name: 'lowerestPrice',
            index: 'LOWEREST_PRICE',
            width: 80,
            formatter:typeFormatter
        },
        {
            label: '我的上一次出价',
            name: 'lastPrice',
            index: 'LAST_PRICE',
            width: 80
        },
        {
            label: '梯度',
            name: 'priceGrad',
            index: 'PRICE_GRAD',
            width: 80
        },
        {
            label: '报价单Id',
            name: 'quotationId',
            index: 'QUOTATION_ID',
            hidden: true
        },
        {
            label: '物料ID',
            name: 'id',
            index: 'ID',
            hidden: true
        },
        {
            label: '物料描述',
            name: 'specification',
            index: 'SPECIFICATION',
            hidden: true
        }
    ];
    $.post(ctx + '/rfqRequest/getCustomItemHeader', {"requestId": requestId}, function (data) {
        var isItem = (data.obj.length == 0);
        if (!isItem) {
            colModel=[{
                label: '物料代码',
                name: 'materialNo',
                index: 'MATERIAL_NO',
                width: 80,
            },
                {
                    label: '物料名称',
                    name: 'materialName',
                    index: 'MATERIAL_NAME',
                    width: 80,
                },
                {
                    label: '型规',
                    name: 'character',
                    index: 'CHARACTER',
                    width: 80
                },
                {
                    label: '数量',
                    name: 'requestAmount',
                    index: 'REQUEST_AMOUNT',
                    width: 80
                },
                {
                    label: '单位',
                    name: 'unit',
                    index: 'UNIT',
                    width: 80
                },
                {
                    label: '报价单Id',
                    name: 'quotationId',
                    index: 'QUOTATION_ID',
                    hidden: true
                },
                {
                    label: '物料ID',
                    name: 'id',
                    index: 'ID',
                    hidden: true
                },
                {
                    label: '物料描述',
                    name: 'specification',
                    index: 'SPECIFICATION',
                    hidden: true
                }];
            $.each(data.obj, function (i, item) {
                var res = {};
                res.label = item.itemName;
                res.name = "itemValue_" + (i + 1);
                res.width = 80;
                colModel.push(res);
            });
            var startPrice = {
                label: '起拍价',
                name: 'startPrice',
                index: 'START_PRICE',
                width: 80
            };
            var lowerestPrice = {
                label: '当前最低价',
                name: 'lowerestPrice',
                index: 'LOWEREST_PRICE',
                width: 80,
                formatter:typeFormatter
            };
            var lastPrice = {
                label: '我的上一次出价',
                name: 'lastPrice',
                index: 'LAST_PRICE',
                width: 80
            };
            var priceGrad = {
                label: '梯度',
                name: 'priceGrad',
                index: 'PRICE_GRAD',
                width: 80
            }
            colModel.push(startPrice);
            colModel.push(lowerestPrice);
            colModel.push(lastPrice);
            colModel.push(priceGrad);
        }
        if(window.sessionStorage.type !='3'){
            var caozuo={
                width: 80,
                label: '操作',
                name: 'id',
                index: 'id',
                sortable:false,
                formatter: actFormatter
                }
            colModel.push(caozuo);
        };
        RFQ.jqGrid('#jqGrid').init({
            url: ctx + '/dacQuotationSingle/dacQuotationItemList',
            colModel: colModel,
            postData: {"id": requestId},
            width: 500,
            sortname: 'ID',
            sortorder: 'ASC',
            pager: "#jqGridPager"
        });
    }, 'json');

    /**定时刷新竞价数据*/
    //setInterval("reloadePrice()","60000");
    var inip = null;
    var stepmax = null;
    $(".btn-table").click(function () {
        quotationClick();
    });
    $("#pricenow-d").html(jqNumToMoney($("#pricenow").val()));
    //输入检测
//		$("#stepn").keydown(function(){
//			if($("#stepn").val() == "0"){
//				$("#stepn").val("");
//			}
//		})

    $.ajax({
        type: "POST",
        url: ctx + '/common/getNowTime',
        success: function (data) {
            setInterval(function () {
                data++;
                $('.serverTime').html(getLocalTime(data));
            }, 1000)
        }
    });

    /**定时刷新竞价数据*/
    setInterval("reloadeItemPrice()","60000");
});

function actFormatter(cellvalue, options, rawObject) {
    var detailBtn = '<span class="ml5"><a class="btn btn-sm btn-info btn-table" data-toggle="modal" data-target="#jjPrice" onclick="quotationClick($(this))"><i class="icon icon-trophy"></i> 去竞价</a></span>';
    return detailBtn;
}
function typeFormatter(cellvalue, options, rawObject){
    var value="";
    if('1'==$("#viewLowerestPriceFlag").val()){
        if(null!=cellvalue){
            value=cellvalue;
        }
        //$("#jqGrid").jqGrid('setLabel',this,"当前最低价");
        $("#jqgh_jqGrid_lowerestPrice").text("当前最低价");
    }else{
        if(null!=cellvalue){
            value=cellvalue;
        }
        //$("#jqGrid").jqGrid('setLabel',7,"排名");
        $("#jqgh_jqGrid_lowerestPrice").text("排名");
    }
    return value;
}
function quotationClick(This) {
    //var tdVar = This.parents("tr").children('td');
    var tdVar = This.parents("tr").attr("id");
    //console.log(tdVar);
    var $jqGrid = $("#jqGrid");
    $("#wuliao-id").html($jqGrid.getCell(tdVar,"materialNo"));
    $("#wuliao-name").html($jqGrid.getCell(tdVar,"materialName"));
    $("#demand-num").html($jqGrid.getCell(tdVar,"requestAmount"));
    $("#wuliao-text").html($jqGrid.getCell(tdVar,"specification"));
    var pricelow = $jqGrid.getCell(tdVar,"lowerestPrice");
    var pricepre = $jqGrid.getCell(tdVar,"lastPrice");
    var startPrice = $jqGrid.getCell(tdVar,"startPrice");
    if('1'!=$("#viewLowerestPriceFlag").val() && ''!=$jqGrid.getCell(tdVar,"lowerestPrice")){
        $("#rank").html("第"+$jqGrid.getCell(tdVar,"lowerestPrice")+"名");
    }
    var arr1 = [];
    if ("1" === $("#lowerestPriceFlag").val()) {
        if (!isNaN(pricelow)&& pricelow !='') {
            arr1.push(pricelow);
        }
        //当当前最低价不为''并且不为null且是数字时为后面添加单位元
        if (!isNaN(pricelow)&& pricelow !=''&&pricelow !=null ) {
            $("#pricelow").next("span").html("元");
        }else{
            $("#pricelow").next("span").html("");
        }
    }
    if (!isNaN(pricepre)&& pricepre !='') {
        arr1.push(pricepre);
    }
    //当上一次出价不为''并且不为null且是数字时为后面添加单位元
    if (!isNaN(pricepre)&& pricepre !=''&&pricepre !=null ) {
        $("#pricepre").next("span").html("元");
    }else{
        $("#pricepre").next("span").html("");
    }
    if (!isNaN(startPrice)&& startPrice !='') {
        arr1.push(startPrice);
    }
    //当起拍价不为''并且不为null且是数字时为后面添加单位元
    if (!isNaN(startPrice)&& startPrice !=''&&startPrice !=null ) {
        $("#startPrice").next("span").html("元");
    }else{
        $("#startPrice").next("span").html("");
    }
    inip = Math.min.apply(Math, arr1);
    $("#pricelow").html(pricelow);
    $("#step").html($jqGrid.getCell(tdVar,"priceGrad"));
    var step = $("#step").html();
    //当梯度不为'&nbsp;'并且不为null且是数字时为后面添加单位元
    if (!isNaN(step)&& step !='&nbsp;'&& step !=''&& step !=null ) {
        $("#step").next("span").html("元");
    }else{
        $("#step").next("span").html("");
    }
    $("#pricepre").html(pricepre);
    $("#startPrice").html(startPrice);
    $("#stepn").val(0);
    $("#pricenow").val(inip.toFixed(4));
    // 初始化pricenow
    if (!inip || inip == Infinity) {
        $('#pricenow').val(0);
    }
    $("#priceCurrent").val(inip.toFixed(4));
    $("#pricenow-d").html(jqNumToMoney($("#pricenow").val()));
    inip = $("#pricenow").val();
    $("#stepmax").val(parseInt(inip / $jqGrid.getCell(tdVar,"priceGrad")));
    $("#quotationId").val($jqGrid.getCell(tdVar,"quotationId"));
    $("#requestItemId").val($jqGrid.getCell(tdVar,"id"));

    /**本次拟出价是否可输入控制*/
    pricenowStateSingle();

}

function assignment() {
    $("#pricenow").val($("#priceCurrent").val() - $('#stepn').val() * $("#step").html());
    $("#pricenow-d").html(jqNumToMoney($("#pricenow").val()));
}
/**提交数据(从jqGrid列表取值，为空时值为：&nbsp;)*/
function submintPrice() {
    $.ajax({
        type: "POST",
        async: false,
        url: ctx + '/dacQuotationSingle/saveDacQuotation',
        data: {
            requestId: $("#requestId").val(),
            requestItemId: $("#requestItemId").val(),
            subtotalTaxed: $("#pricenow").val(),
            availableCount: $("#demand-num").html(),
            quotationId: $("#quotationId").val()==="&nbsp;"? "" : $("#quotationId").val(),
            tax: $("#extendField4  option:selected").val()
        },
        success: function () {
            reloadeItemPrice();
        },
        error: function () {
            $.zui.messager.show('重新载入数据失败！', {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
        }
    });

}

function reloadeItemPrice() {
    var trVar = $('#jqGrid').children('tbody').children('tr');
    var requestItemIdList = [];
    for (var i = 1; i < trVar.length; i++) {
        var trId = trVar.eq(i).attr("id");
        var itemId = $('#jqGrid').getCell(trId,"id");
        requestItemIdList.push(itemId);
    }
    $.ajax({
        type: "POST",
        async: false,
        url: ctx + '/dacQuotationSingle/reloadDacQuotationItem',
        data: {
            requestId: $("#requestId").val(),
            requestItemId: JSON.stringify(requestItemIdList)
        },
        success: function(data){
            var trNew = $('#jqGrid').children('tbody').children('tr');
            $.each(data.list,function(i,d){
                var trNewId = trNew.eq(i+1).attr("id");
                //console.log(trNewId);
                $("#jqGrid").setCell(trNewId,"lowerestPrice",d.lowerestPrice);
                $("#jqGrid").setCell(trNewId,"lastPrice",d.lastPrice);
                $("#jqGrid").setCell(trNewId,"quotationId",d.quotationId);
            });

            var clock = $('#clock').data("_flipclock");
            clock.setTime(data.quotationBaseVo.countDown);

        }});
}
/**本次拟出价是否可输入控制*/
function pricenowStateSingle () {
    if ($("#step").html() === '&nbsp;'|| Number($("#step").html()) === 0 || inip === Infinity || inip === '') {
        $("#pricenow").attr("disabled", false);
        $("#pricenow").attr("onkeyup","checkPriceNow()");
       // $("#pricenow").attr("onafterpaste","checkPriceNow()");
       // $("#pricenow").attr("onblur","checkPriceNow()");
    } else {
        $("#pricenow").attr("disabled", true);
    }
}
//出价校验
function checkPriceNow () {
    var pricenow = $("#pricenow").val();//本次拟拍价
    var flag = true;
    if ($("#startPrice").html() !== undefined && Number(pricenow) > Number($("#startPrice").html())) {
        $.zui.messager.show('本次拟出价不可大于起拍价！', {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
        $("#pricenow").focus();
        flag = false;
    }
    if ($("#pricelow").html() !== undefined && $("#pricelow").html() !== '&nbsp;' && $("#pricelow").html() !== '' && Number(pricenow) > Number($("#pricelow").html())) {
        $.zui.messager.show('本次拟出价不可大于当前最低价！', {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
        $("#pricenow").focus();
        flag = false;
    }
    if ($("#pricepre").html() !== undefined && $("#pricepre").html() !== '&nbsp;' && $("#pricepre").html() !== '' && Number(pricenow) > Number($("#pricepre").html())) {
        $.zui.messager.show('本次拟出价不可大于我的上一次出价！', {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
        $("#pricenow").focus();
        flag = false;
    }
    if (pricenow == '' || Number(pricenow) < 0) {
        $.zui.messager.show('本次拟出价不可小于0！', {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
        $("#pricenow").focus();
        flag = false;
    }
    if (flag === false) {
        $("#confirm").attr("disabled", true);//确定按钮置灰
    } else {
        $("#pricenow-d").html(jqNumToMoney(pricenow));
        $("#confirm").attr("disabled", false);//确定按钮激活
    }

}

//竞价单详情
function show(data){
    window.sessionStorage.designateResult_tax=null;
    location.href=ctx+"/dacReverseAuction/reverseAuctionDetail?id="+data;
}